package com.feng.chat.utils;

import com.alibaba.fastjson.JSON;
import com.feng.chat.dto.AddressDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * 获取IP地址及详细的地域信息
 */

@Component
public class IpUtil {

    @Autowired
    private RestTemplate restTemplate;

    public AddressDTO getUserAddress(HttpServletRequest request)  {
        String ip = "";

        // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for

        if  (request.getHeader("x-forwarded-for") == null)  {
            ip = request.getRemoteAddr();
        }  else  {

            ip = request.getHeader("x-forwarded-for");

        }

        if  ("127.0.0.1".equals(ip))  {
            // 获取本机真正的ip地址
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }

        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
//        String ipUrl="https://ip.cn/api/index?ip="+ip+"&type=1";

        String ipUrl="http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true";

        String json = restTemplate.getForObject(ipUrl, String.class);
        return JSON.parseObject(json,AddressDTO.class);
        /*try {
            ResponseEntity response = restTemplate.exchange(ipUrl, HttpMethod.GET, new HttpEntity<>(headers), AddressDTO.class);
            return (AddressDTO) response.getBody();
        }catch (Exception e){
            AddressDTO addressDTO = new AddressDTO();
            *//*addressDTO.setAddress("   内网IP 内网IP");
            addressDTO.setCode(200);
            addressDTO.setIp("192.168.180.1");
            addressDTO.setIsDomain(1);
            addressDTO.setRs(2);*//*
            return addressDTO;
        }*/

    }
}


